<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use catetree\Catetree;
class Attr extends Controller
{
	public function lst()
	{	
		$typeId=input('type_id');
		if($typeId)
		{
			$map['type_id']=['=',$typeId];
		}else
		{
			$map=1;
		}
		$attrRes=db('attr')->alias('a')->field('a.*,t.type_name')->join('type t','t.id=a.type_id')->where($map)->paginate('10');
		$settitle=settitle('商品属性');
		$this->assign(array(
			'typeId'=>$typeId,
			'settitle'=>$settitle,
			'attrRes'=>$attrRes
		));
		return view();
	}
	public function add()
	{		
		$typeId=input('type_id');
		$attrObj=db('attr');
		$typeObj=db('type');
		$type=new Catetree();
		if(request()->isPost())
		{
			$data=input('post.');
			//如果是多选则 将中文逗号替换为英文',';
			if(!empty($data['attr_values']))
			{
				$data['attr_values']=str_replace('，',',',$data['attr_values']);
			}
			//验证
    		$validate = validate('attr');
    		if(!$validate->check($data)){
			    $this->error($validate->getError());
			}
			//处理上传图片
			$add=$attrObj->insert($data);
			if($add)
			{
				return $this->redirect('lst',array('type_id'=>$typeId));
				//$this->success('添加商品属性成功',url('lst'));
			}else
			{
				$this->error('添加商品属性失败');
			}
		}
		$typeRes=$typeObj->select();
		$settitle=settitle('商品属性');
		$this->assign(
			array(
				'typeId'=>$typeId,
				'settitle'=>$settitle,
				'typeRes'=>$typeRes
			)
		);
		return view();
	}
	public function edit()
	{
		$typeId=input('type_id');
		$attrObj=db('attr');
		$typeObj=db('type');
		$id=input('id');
		if(request()->isPost())
		{	
			$data=input('post.');
			//如果是多选则 将中文逗号替换为英文',';
			if(!empty($data['attr_values']))
			{
				$data['attr_values']=str_replace('，',',',$data['attr_values']);
			}
			//验证
    		$validate = validate('attr');
    		if(!$validate->check($data)){
			    $this->error($validate->getError());
			}
			//处理上传图片
			$save=db('attr')->update($data);
			if($save!==false)
			{
				return $this->redirect('lst',array('type_id'=>$typeId));
				//$this->success('修改商品属性成功',url('lst'));
			}else
			{
				$this->error('修改商品属性失败');
			}
		}
		$attrs=$attrObj->find($id);
		$typeRes=$typeObj->select();
		$settitle=settitle('商品属性');
		$this->assign(
			array(
			'typeId'=>$typeId,
			'attrs'=>$attrs,
			'settitle'=>$settitle,
			'typeRes'=>$typeRes
		)
	);
		return view();
	}

	public function del($id)
	{	
		$del=db('attr')->delete($id);
		if($del)
		{
			$this->success('删除商品属性成功',url('lst'));
		}else
		{
			$this->error('删除商品属性失败');
		}
	}
	//商品中选择不同类型展示该类型下的属性
	public function ajaxGetAttr()
	{
		$typeId=input('post.type_id');
		$attrRes=db('attr')->where(array('type_id'=>$typeId))->select();
		echo json_encode($attrRes);

	}
}
